package org.yuanqiframework.yuanqi.web.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.pattern.PathPattern;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component
public class SpringMvcUtils {


    @Qualifier("requestMappingHandlerMapping")
    @Resource
    private RequestMappingHandlerMapping handlerMapping;

    public List<Map<String, String>> getAllUrl() {
        ArrayList<Map<String, String>> maps = new ArrayList<>();

        // 获取URL与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = handlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            RequestMappingInfo rm = m.getKey();
            HandlerMethod method = m.getValue();
            if (rm.getPathPatternsCondition() != null) {
                HashMap<String, String> stringStringHashMap = new LinkedHashMap<>();

                Set<RequestMethod> methodsSet = rm.getMethodsCondition().getMethods();
                Set<PathPattern> patternsSet = rm.getPathPatternsCondition().getPatterns();
                if (!methodsSet.isEmpty()) {
                    String httpMethod = methodsSet.toArray()[0].toString();
                    String httpUrl = patternsSet.toArray()[0].toString();
                    stringStringHashMap.put("httpMethod", httpMethod);
                    stringStringHashMap.put("httpUrl", httpUrl);
                    stringStringHashMap.put("id", Base64.getEncoder().encodeToString((httpMethod +"<=>"+ httpUrl).getBytes()));
                    stringStringHashMap.put("className", method.getMethod().getDeclaringClass().getName());
                    stringStringHashMap.put("method", method.getMethod().getName());
                    maps.add(stringStringHashMap);
                }
            }
        }
        return maps;
    }
}
